<template>
  <div>
    <ych-modal
      :fullscreen="true"
      :visible="visible"
      :bodyStyle="bodyStyle"
      :confirmLoading="confirmLoading"
      @cancel="handleCancel"
      :closable="false"
      :footer="null"
      :destroyOnClose="true"
    >
      <iframe ref="iframe" v-if="visible" :src="iframeUrl" class="appDesignIframe" :style="{height: height}"/>
    </ych-modal>

    <select-dict-dialog ref="selectDictDialog" @selectFinished="selectDictOk" :groupId="groupId"></select-dict-dialog>
    <select-sql-config-dialog ref="selectSqlConfigDialog" @selectFinished="selectSqlConfigOk" :groupId="groupId"></select-sql-config-dialog>
    <k-json-modal ref="jsonModal"/>
    <importJsonModal ref="importJsonModal" @importJson="importJson"/>
    <OpenScriptDialog ref="scriptDialog" @selectFinished="showScriptDialogOk" helpCode="mobile_script"></OpenScriptDialog>
  </div>
</template>

<script>

import {ajaxGetDictItems, ajaxGetSqlConfigItems} from '@/api/api';
import {putAction, getAction, postAction} from '@/api/manage'
import YchConstant from "@/api/YchConstant";
import SelectDictDialog from "../select/dialog/SelectDictDialog";
import SelectSqlConfigDialog from "../select/dialog/SelectSqlConfigDialog";
import kJsonModal from "./designer/packages/KFormDesign/module/jsonModal";
import importJsonModal from "./designer/packages/KFormDesign/module/importJsonModal";
import OpenScriptDialog from "./actAppView/OpenScriptDialog";

export default {
  name: 'AppFormDesignerDialog',
  props: {
    groupId: {
      type: String,
      required: true
    },
  },
  components: {
    SelectDictDialog,
    SelectSqlConfigDialog,
    kJsonModal,
    importJsonModal,
    OpenScriptDialog,
  },
  data() {
    return {
      title: this.$t('m.eform.appform.other.mobile_form_design'),
      model: {},
      visible: false,
      bodyStyle: {
        padding: 0,
        margin: 0
      },
      iframeBaseUrl: '/app/index.html',
      // iframeBaseUrl: 'http://localhost:8081',
      iframeUrl: null,
      height: document.body.clientHeight - 5 + 'px',
      readyForReceiving: false,
      confirmLoading: false,
      url: {
        editDesignData: YchConstant.PREFIX_EFORM + '/manage/actAppForm/editMobileDesignData',
        getBoTreeByKey: YchConstant.PREFIX_EFORM + '/manage/actAppObject/getBoTreeByKey',
        executeRuleByCode: YchConstant.PREFIX_SYSTEM + '/fillRule/executeRuleByCode/',
        getOrgListByIds: YchConstant.PREFIX_SYSTEM + '/sysOrg/queryByIds',
        getUserListByIds: YchConstant.PREFIX_SYSTEM + '/user/queryByIds',
        getRootOrgTreeList: YchConstant.PREFIX_SYSTEM + '/sysOrg/getRootOrgTree',
        getSubDeptTreeByDepartIdUrl: YchConstant.PREFIX_SYSTEM + '/sysOrg/getSubDeptTreeByDepartId',
        getUserListByDeptId: YchConstant.PREFIX_SYSTEM + '/user/getUserListByDeptId',
      }
    }
  },
  methods: {
    handleOpenImportJsonModal (data) {
      this.$refs.importJsonModal.jsonData = data
      this.$refs.importJsonModal.visible = true
    },
    importJson(data) {
      this.sendMessage("handleSetData", JSON.parse(data))
    },
    handleOpenJsonModal(data) {
      this.$refs.jsonModal.jsonData = data
      this.$refs.jsonModal.visible = true
    },
    selectDict(data, callbackFuncName) {
      this.callbackFuncName = callbackFuncName
      this.$refs.selectDictDialog.radio = true;
      this.$refs.selectDictDialog.visible = true;
    },
    selectDictOk(selectedRowKeys, selectionRows) {
      let dictOption;
      if (selectionRows) {
        dictOption = {
          dictCode: selectionRows[0].dictCode,
          dictName: selectionRows[0].dictName
        }
      } else {
        dictOption = {}
      }
      this.sendMessage(this.callbackFuncName, dictOption)
    },
    showScriptDialog(data, callbackFuncName) {
      this.callbackFuncName = callbackFuncName
      const eventText = data.eventText || ''
      this.$refs.scriptDialog.open(eventText)
    },
    showScriptDialogOk(text) {
      const eventText = text || ''
      this.sendMessage(this.callbackFuncName, {eventText})
    },
    selectSqlConfig(data, callbackFuncName) {
      this.callbackFuncName = callbackFuncName
      this.$refs.selectSqlConfigDialog.radio = true;
      this.$refs.selectSqlConfigDialog.visible = true;
    },
    selectSqlConfigOk(selectedRowKeys, selectionRows) {
      let sqlConfig;
      if (selectionRows) {
        sqlConfig = {
          sqlCode: selectionRows[0].sqlCode,
          sqlName: selectionRows[0].sqlName
        }
      } else {
        sqlConfig = {}
      }
      this.sendMessage(this.callbackFuncName, sqlConfig)
    },
    ajaxGetUserByIds({userIds}, callbackFuncName) {
      getAction(this.url.getUserListByIds, {userIds: userIds}).then((res) => {
        if (res.success) {
          this.sendMessage(callbackFuncName, {result: res.result})
        } else {
          this.messageUtil.warning(res.message)
        }
      })
    },
    ajaxGetDeptByIds({deptIds}, callbackFuncName) {
      getAction(this.url.getOrgListByIds, {ids: deptIds}).then((res) => {
        if (res.success) {
          this.sendMessage(callbackFuncName, {result: res.result})
        } else {
          this.messageUtil.warning(res.message)
        }
      })
    },
    ajaxGetSerialno({ruleCode}, callbackFuncName) {
      putAction(this.url.executeRuleByCode + ruleCode, {}).then((res) => {
        if (res.success) {
          this.sendMessage(callbackFuncName, {result: res.result})
        } else {
          this.messageUtil.warning(res.message)
        }
      })
    },
    ajaxGetDictItems({code}, callbackFuncName) {
      ajaxGetDictItems(code, null).then((res) => {
        if (res.success) {
          this.sendMessage(callbackFuncName, {result: res.result})
        } else {
          this.messageUtil.warning(res.message)
        }
      })
    },
    ajaxGetSqlConfigItems({code}, callbackFuncName) {
      ajaxGetSqlConfigItems(code, null).then((res) => {
        if (res.success) {
          this.sendMessage(callbackFuncName, {result: res.result})
        } else {
          this.messageUtil.warning(res.message)
        }
      })
    },
    getRootOrgTreeList({}, callbackFuncName) {
      getAction(this.url.getRootOrgTreeList).then(res => {
        if (res.success) {
          this.sendMessage(callbackFuncName, {result: res.result})
        } else {
          this.messageUtil.warning(res.message)
        }
      })
    },
    getSubDeptTreeByDepartIdUrl({deptId}, callbackFuncName) {
      getAction(this.url.getSubDeptTreeByDepartIdUrl, {departId: deptId}).then(res => {
        if (res.success) {
          this.sendMessage(callbackFuncName, {result: res.result})
        } else {
          this.messageUtil.warning(res.message)
        }
      })
    },
    getUserListByDeptId({deptId}, callbackFuncName) {
      postAction(this.url.getUserListByDeptId + "?deptId=" + deptId + "&sub=false", {}).then(res => {
        if (res.success) {
          this.sendMessage(callbackFuncName, {result: res.result})
        } else {
          this.messageUtil.warning(res.message)
        }
      })
    },
    open(record) {
      this.model = record
      this.iframeUrl = this.iframeBaseUrl + "?id=" + this.model.id
      this.visible = true
    },
    handleOk(data) {
      const that = this
      this.$confirm({
        title: this.$t('m.common.button.save'),
        content: this.$t('m.common.tip.save_confirm'),
        onOk() {
          that.confirmLoading = true
          putAction(that.url.editDesignData + '?id=' + that.model.id, data).then((res) => {
            if (res.success) {
              that.messageUtil.success(that.$t('m.eform.formDesign.label.bao-cun-cheng-gong'))
              that.$emit('ok')
              that.handleCancel()
            } else {
              that.messageUtil.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        }
      });
    },
    handleCancel() {
      this.visible = false
      this.readyForReceiving = false
    },
    createBoTreeData(boKey) {
      this.confirmLoading = true
      getAction(this.url.getBoTreeByKey, {
        boKey: boKey
      }).then((res) => {
        if (res.success) {
          let boTree = res.result.boTree
          let colTree = res.result.colTree
          let tableTree = res.result.tableTree
          const message = {
            tableName: tableTree[0].value,
            tableTree: tableTree,
            colTree: colTree,
            boTreeData: boTree
          }
          this.sendMessage("createBoTreeData", message)
        } else {
          this.messageUtil.warning(res.message)
        }
      }).finally(() => {
        this.confirmLoading = false
      })
    },
    handleMessage(event) {
      if (typeof event.data !== 'string' || event.data.indexOf("cmd") === -1) {
        //console.log(event)
        return
      }
      const message = JSON.parse(event.data)
      if (message.cmd === 'readyForReceiving') {
        this.readyForReceiving = true
      } else if (typeof this[message.cmd] === "function") {
        this[message.cmd].apply(this, [message.data, message.callbackFuncName])
      } else {
        //console.log(event)
      }
    },
    sendMessage(cmd, data) {
      const message = {
        cmd: cmd,
        data: data || {}
      }
      const iframeWin = this.$refs.iframe.contentWindow
      iframeWin.postMessage(JSON.stringify(message), '*')
    }
  },
  watch: {
    readyForReceiving: {
      handler(value) {
        if (value) {
          //页面元素
          let data = this.model.mobileModel
          this.title = this.model.formName || this.$t('m.eform.appform.other.mobile_form_design')
          this.sendMessage("setTitle", {
            title: this.title
          })
          if (data) {
            this.sendMessage("handleSetData", JSON.parse(data))
          }
          const boKey = this.model.objectCode
          if (boKey) {
            this.createBoTreeData(boKey)
          }
        }
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      window.addEventListener('message', this.handleMessage)
    });
  },
  destroyed() {
    // 注意移除监听！
    window.removeEventListener('message', this.handleMessage)
  },
}
</script>
<style lang="less">
.appDesignIframe {
  width: 100%;
  border: 0;
  margin: 0;
  padding: 0;
}
</style>
